package impl;

import anaydis.sort.SorterType;
import com.sun.istack.internal.NotNull;

import java.util.Comparator;
import java.util.List;
import java.util.Locale;

public class HeapSorter extends AbstractSorter {

    public HeapSorter() {
        super(SorterType.HEAP);
    }

    public <T> void sort(Comparator<T> comparator, List<T> list) {
        sort(comparator, list, 0, list.size() - 1);
    }

    protected <T> void sort(Comparator<T> comparator, List<T> list, int left, int N) {
        for (int k = (N - 1) / 2; k >= left; k--) {
            sink(comparator, list, k, N);
        }
        while (N > left) {
            swap(list, left, N--);
            sink(comparator, list, left, N);
        }
    }

    private <T> void sink(Comparator<T> comparator, List<T> list, int k, int N) {
        while ((((k + 1) * 2) - 1) <= N) {
            int j = ((k + 1) * 2) - 1;
            if (j < N && !greater(comparator, list, j, j + 1)) {
                j++;
            }
            if (greater(comparator, list, k, j)) break;
            swap(list, k, j);
            k = j;
        }
    }

    public <T> void sort(Locale loc, @NotNull Comparator<T> tComparator, @NotNull List<T> ts) {
        for (int i = ts.size() / 2; i >= 0; i--)
            subSort(loc, tComparator, ts, i, ts.size());
        for (int i = ts.size() - 1; i > 0; i--) {
            swap(ts, 0, i);
            subSort(loc, tComparator, ts, 0, i);
        }
    }

    private static int leftChild(int i) {
        return 2 * i + 1;
    }

        private <T> void subSort(Locale loc, Comparator<T> tComparator, List<T> ts, int i, int n) {
        int child;

        for (ts.get(i); leftChild(i) < n; i = child) {
            child = leftChild(i);
            if (child != n - 1 && greater(loc, tComparator, ts, child + 1, (child)))
                child++;
            if (greater(loc, tComparator, ts, child, i))
                swap(ts, i, child);
            else
                break;
        }
    }
}
